<template>
	<view class="install-container" style="margin-bottom: 30rpx;">
	
		<!-- 用户信息 -->
		<!-- 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，
		这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则 -->
		<uni-forms :value="params" ref="form" validateTrigger="bind" class="word5">
			<uni-forms-item required label="申请人：" name="领取人员">
				<input disabled placeholder="请选择申请人" v-model="params['领取人员']" @input="binddata('起始楼层号',$event.detail.value)">
			</uni-forms-item>
			<!-- <uni-forms-item required label="申请单位：" name="所属单位">
				<input disabled type="number" v-model="params['所属单位']" placeholder="请输入申请单位" @input="binddata('所属单位',$event.detail.value)" >
			</uni-forms-item> -->
			<uni-forms-item required label="申请仓库：" name="仓库id">
				<view :class="label == '请选择申请仓库' ? 'color':''" class="tap" @click="handleTap('picker')">{{label}}</view>
				<lb-picker ref="picker" @click="handleTap('picker')" @input="binddata('仓库id',$event)" v-model="params['仓库id']"
				 mode="selector" :list="storeList" :dataset="{ name: 'label' }" @confirm="handleConfirm" @cancel="handleCancel">
				</lb-picker>
			</uni-forms-item>
			<uni-forms-item required label="申请原因：" name="备注">
				<input type="text" v-model="params['备注']" placeholder="请输入申请原因" @input="binddata('备注',$event.detail.value)" >
			</uni-forms-item>
			<!-- <uni-forms-item required label="所属楼栋：" name="楼栋id">
				<view :class="label == '请选择所属楼栋' ? 'color':''" class="tap" @click="handleTap('picker')">{{label}}</view>
				<lb-picker ref="picker" @click="handleTap('picker')" v-model="params['楼栋id']"
				 mode="selector" :list="buildList" :dataset="{ name: 'label' }" @confirm="handleConfirm" @cancel="handleCancel">
				</lb-picker>
			</uni-forms-item> -->
			<button class="material-form-btn" @click="submitForm">提交</button>
		</uni-forms>
		<view class="line"></view>
		<view v-if="params['材料清单'].length">
			<view class="detail-title">
				<text>申请明细</text>
			</view>
			<applyItem @onShow="handleShow" :storeId="params['仓库id']" @delete="handleDelete" :classList="classList" :ref="'material'+item.id" :params.sync="item" :key="item.id" v-for="item in params['材料清单']"></applyItem>			
		</view>
		<view @click="onAdd" class="choose-box">
			<text style="font-size: 50rpx;margin-right: 10rpx;">+</text>
			<text>添加</text>
		</view>
		
		<!-- <view class="title">
			<view class="left">申领列表</view>
			<view class="right">
				<text class="add" @click="goAdd">
					+
				</text>
				<text @click="goAdd" style="color: #1152FC;">添加</text>
			</view>
		</view>
		<view class="choose-container">
			<apply-item @change="handleChange" @delete="handleDelete" v-if="params['材料清单'].length" :applyList="params['材料清单']"></apply-item>
			<view v-else>
				<van-empty description="暂无耗材"></van-empty>
			</view>
		</view> -->
		 
	</view>
</template>

<script>
	import ApplyItem from './applyItem.vue'
	import LbPicker from '@/components/lb-picker/index.vue'
	import dayjs from 'dayjs'
	export default {
		components: {
			LbPicker,
			ApplyItem
		},
		data() {
			return {
				classList: [],
				storeList: [],
				label: '请选择申请仓库',
				params: {
					仓库id: null,	
					出库时间: null,		
					领取人员: null,
					所属单位: null,
					所属单位id: null,
					所属机构id: this.$config.groupId,
					所属机构: uni.getStorageSync('groupName'),
					备注: '',
					材料清单: []
				},
				params1: {
					所属机构: 0,
					pagination: {
						current: 1,
						pageSize: 100
					},
					sorter: {
						field: "id",
						order: 0
					}
				},
				params2: {
					类型分类: 2,
					pagination: {
						current: 1,
						pageSize: 1000
					},
					sorter: {
						field: "id",
						order: 0
					}
				},
				
				//表单验证规则
				rules: {
					领取人员: {
						rules: [{
							required: true,
							errorMessage: '请填写申请人',
						}]
					},
					所属单位: {
						rules: [{
							required: true,
							errorMessage: '请填写申请单位',
						}]
					},
					仓库id: {
						rules: [{
							required: true,
							errorMessage: '请选择申请仓库',
						}]
					},
					备注: {
						rules: [{
							required: true,
							errorMessage: '请填写申请原因',
						}]
					}
				}
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad(options) {
		},
		onShow() {
			this.getStoreList()
			this.params.领取人员 = uni.getStorageSync('userInfo').name
			// this.params.所属单位 =  uni.getStorageSync('label')
			this.params.领取人员id = uni.getStorageSync('userInfo').id
			// this.params.所属单位id = uni.getStorageSync('currentUnitId')
			this.params.所属机构 = uni.getStorageSync('groupName')
		},
		onUnload() {
			// console.log('页面卸载了')
			uni.removeStorageSync('applyList')
		},
		methods: {
			handleShow() {
				console.log('params', this.params)
			},
			handleDelete(e) {
				// console.log(e)
				let applyList = uni.getStorageSync('applyList') || []
				const index = this.params.材料清单.findIndex(item => item.id === e)
				const aIndex = applyList.findIndex(item => item.id === e)
				if(aIndex > -1) {
					applyList.splice(aIndex, 1)
					uni.setStorageSync('applyList', applyList)
				}
				this.params.材料清单.splice(index, 1)
			},
			
			async getClassList() {
				uni.showLoading({
					mask: true
				})
				const res = await this.$http.post('/property/typeSetting/list', this.params2)
				if(res.code === 10000) {
					// console.log(res)
					res.data.list = res.data.list || []
					res.data.list.forEach(item => {
						item.text = item.类型名称
						item.value = item.类型id
					})
					this.classList = res.data.list
				}
			},
			onAdd() {
				if(!this.params.仓库id) {
					uni.showToast({
						title: '请选择出库仓库',
						icon: 'none'
					})
					return
				}
				this.params.材料清单.push({
					id: Date.now(),
					类型名称: null,
					物料名称: null,
					物料id: null,
					数量	: 1,
					计量单位: null,
					规格型号: null
				})
				// console.log(this.params.材料清单)
			},
			getStoreList() {
				this.$http.post('/property/warehouse/list', this.params1).then(res => {
					if(res.code === 10000) {
						res.data.list = res.data.list || []
						res.data.list.forEach(item => {
							item.label = item.仓库名称
							item.value = item.仓库id
						})
						this.storeList = res.data.list
					}
				})
			},
			handleTap(name) {
				this.$refs[name].show()
			},
			handleConfirm(e) {
				// console.log(this.params.户主关系)
				if (e) {
					const name = e.dataset.name
					const label = e.item.label
					this.params.材料清单 = []
					uni.removeStorageSync('applyList')
					this.getClassList()
					if (name && label) {
						this[name] = label
					}
				}
			},
			submitForm(form) {
				//校验所有材料表单
				let validated = true
				// let isValidate = this.params.材料清单.every(item => this.$refs['cailiao'+item.id][0].validate())
				for(let i = 0; i < this.params.材料清单.length; i++) {
					if(!this.$refs['material'+this.params.材料清单[i].id][0].validate())	{
						validated = false
					}
				}
				if(validated){
					//提交数据到后端
					this.$refs.form.submit().then(res => {
						// res.检查点id = this.params.检查点id
						console.log('通过')
						let applyList = uni.getStorageSync('applyList') || []
						let list = applyList.filter(item => item.数量)
						list.forEach(item => {
							if(parseInt(item.数量) < 0) {
								item.数量 = 1
							}
						})
						if(!list.length && applyList.length) {
							uni.showToast({
								title: '库存为0的耗材无法申请',
								icon: 'none'
							})
							return
						}
						let obj = Object.assign({}, this.params, {材料清单: list})
						
						console.log('obj', obj)
						// console.log('params', this.params)
						// const isEnough = this.params.材料清单.every(item => item.物料数量) 
						// if(!isEnough) {
						// 	uni.showToast({
						// 		title: '提交失败,存在库存为0的耗材',
						// 		icon: 'none'
						// 	})
						// 	return
						// }
						this.applyMaterial(obj)
					}).catch(err => {
						console.log('表单错误信息：', err);
						uni.showToast({
							icon: 'none',
							title: "表单字段填写错误，请检查"
						})
					})
				}
			},
			applyMaterial(params) {
				uni.showLoading()
				this.$http.post('/property/outstore/create', params).then(res => {
					if(res.code === 10000) {
						uni.redirectTo({
							url: '/ticketSystem/acceptSuccess/acceptSuccess?path=/pages/service/service' + '&title=返回服务页面'
						})
						uni.removeStorageSync('applyList')
					}else if(res.code === 50001) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.detail-title {
		padding-left: 40rpx;
		padding-top: 20rpx;
		position: relative;
		font-size: 32rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		&:before {
			position: absolute;
			content: '';
			width: 6rpx;
			height: 36rpx;
			left: 20rpx;
			top: 24rpx;
			background-color: #1064E9;;
		}
	}
	.choose-box {
		font-size: 40rpx;
		color: #1152FC;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
	}
	.title {
		position: relative;
		padding: 0 20rpx 0 40rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 40rpx;
		font-size: 34rpx;
		.left {
			font-size: 32rpx;
			&:before {
				content: '';
				position: absolute;
				top: 10rpx;
				left: 24rpx;
				width: 6rpx;
				height: 34rpx;
				background-color: #1152FC;
			}
		}
		.right {
			// display: flex;
		}
		.add {
			font-size: 32rpx;
			font-weight: bold;
			color: #1152FC;
			margin-right: 10rpx;
		}
	}
	.line {
		margin-top: 100rpx;
		// margin-bottom: 40rpx;
		width: 710rpx;
		margin-left: 20rpx;
		height: 2rpx;
		background-color: #ccc;
	}
	.install-container {
		padding-bottom: 90rpx;
		// height: 100vh;
		// background-color: #F8F8F8;
	}
	.color {
		color: #808080;
	}
	.tap {
		display: flex;
		align-items: center;
	}
</style>

